/*
 * @Description: 本地缓存对象 Storage | Cookie
 * @Author: wangqi
 * @Date: 2022-04-18 15:08:18
 * @LastEditTime: 2022-04-18 15:33:51
 */

// 默认缓存期限为7天
const DEFAULT_CACHE_TIME = 60 * 60 * 24 * 7;

function createStorage({ prefixKey = '', storage = localStorage } = {}) {
  const Storage = class {
    private prefixKey?: string = prefixKey;
    private storage = storage;

    private getKey(key: string) {
      return `${this.prefixKey}${key}`.toUpperCase();
    }

    /**
     * @description: 设置缓存
     * @param {string} key      缓存名
     * @param {any} value       缓存值
     * @param {number} expire   过期时间
     * @return {*}
     */
    set(key: string, value: any, expire: number | null = DEFAULT_CACHE_TIME) {
      const stringData = JSON.stringify({
        value,
        expire: expire !== null ? +new Date() + expire * 1000 : null,
      });
      this.storage.setItem(this.getKey(key), stringData);
    }

    /**
     * @description: 获取缓存
     * @param {string} key      缓存名
     * @param {any} def         默认返回值
     * @return {*}
     */
    get<T = any>(key: string, def: any = null): T {
      const item = this.storage.getItem(this.getKey(key));
      if (item) {
        try {
          const data = JSON.parse(item);
          const { value, expire } = data;
          // 在有效期内直接返回
          if (expire > Date.now()) {
            return value;
          }
          // 不在有效期内删除多余的key
          this.remove(this.getKey(key));
        } catch (error) {
          console.log(`读取Storage中${key}失败!`);

          return def;
        }
      }

      return def;
    }

    /**
     * @description: 删除指定缓存
     * @param {string} key      缓存名
     * @return {*}
     */
    remove(key: string) {
      this.storage.removeItem(this.getKey(key));
    }

    /**
     * 清空所有缓存
     * @param
     */
    clear(): void {
      this.storage.clear();
    }
  };

  return new Storage();
}

const Storage = createStorage();
export { Storage };
export default Storage;
